package main

import (
	"bufio"

	"io"
	"os"
	"strings"
)

type DrTxtReader struct {
	DrAbstractObject
	file   *os.File
	reader *bufio.Reader
}

func NewTxtReader(filename string) *DrTxtReader {
	var result *DrTxtReader
	result = new(DrTxtReader)
	var err error

	result.file, err = os.Open(filename)
	if err != nil {
		panic(err.Error())
	}
	result.reader = bufio.NewReader(result.file)
	return result
}
func (self *DrTxtReader) Close() {
	self.file.Close()
}

//读入一行，至换行符处结束
func (self *DrTxtReader) ReadLine() string {
	str, err := self.reader.ReadString('\n')
	if err == io.EOF {
		str = ""
	}
	return str
}

//读取全部行，行之间由换行符来分隔
func (self *DrTxtReader) ReadLines() []string {
	result := make([]string, 0, 100)
	for {
		str, err := self.reader.ReadString('\n')
		if str != "" {
			result = append(result, str)
		}
		if err == io.EOF {
			break
		}

	}
	return result
}

//读取指定数目的，行之间由换行符来分隔
func (self *DrTxtReader) ReadLines2(rows int) []string {
	result := make([]string, 0, rows)
	for i := 0; i < rows; i++ {
		str, err := self.reader.ReadString('\n')
		if str != "" {
			result = append(result, str)
		}
		if err == io.EOF {
			break
		}

	}
	return result
}

//读入整个文件当作一条字符串，不分行，换行符被保留在字符串
func (self *DrTxtReader) ReadAll() string {
	result := ""
	for {
		str, err := self.reader.ReadString('\n')
		if err == io.EOF {
			str = ""
			break
		}
		result += str
	}
	return result
}

//读入一行，但按照空格和tab把字符串分割为多个
func (self *DrTxtReader) ReadLineSplit() []string {
	str := self.ReadLine()
	strs := strings.Split(str, " ")
	str2 := strings.Split(str, "\t")
	if len(strs) > len(str2) {
		return strs
	} else {
		return str2
	}
}

//按行读入所有字符串后，把字符串再按照分隔符分隔开，变成字符串矩阵
func (self *DrTxtReader) ReadMatrix(nSkipLine int, seperator string) [][]string {
	self.ReadLines2(nSkipLine)
	result := make([][]string, 0, 100)
	for {
		str, err := self.reader.ReadString('\n')
		if str != "" {
			strs := strings.Split(str, seperator)
			result = append(result, strs)
		}
		if err == io.EOF {
			break
		}
	}
	return result
}
func (self *DrTxtReader) executeMethod(funcName string, prams []IObject) IObject {
	if funcName == "readline" {
		return NewStr(self.ReadLine())
	}
	if funcName == "readlines" {
		strs := self.ReadLines()
		return NewStrArray1(strs)
	}
	if funcName == "readlines2" {
		strs := self.ReadLines2(prams[1].getInt())
		return NewStrArray1(strs)
	}
	if funcName == "readMatrix" {
		strlines := self.ReadMatrix(prams[1].getInt(), prams[2].(*DrString).AsString())
		return NewStrArray2(strlines)
	}

	panic("funcName is inexist for this object")

	panic("not implemented for the method:" + funcName)

}
